package cluster

import (
	"github.com/samuel/go-zookeeper/zk"
	log "github.com/sirupsen/logrus"
	"xc/app/zookeeper"
)

// Cluster 集群
type Cluster struct {
	path  string   //zk路径
	data  []byte   //zk数据
	flags int32    //zk标示
	acl   []zk.ACL //zk权限
}

var cluster *Cluster

// InitCluster 集群初始化
func InitCluster() *Cluster {
	c := new(Cluster)
	c.initData()
	c.check()

	cluster = c

	return c
}

// initData 集群初始化数据
func (c *Cluster) initData() {
	c.path = zookeeper.GetClusterPath()
	c.data = []byte("cluster info")
	c.acl = zk.WorldACL(zk.PermAll)
	c.flags = 0
}

// check 集群检查
func (c *Cluster) check() {
	exist, _, err := zookeeper.Connect().Exists(c.path)
	if err != nil {
		log.Panic("[cluster]", err)
	}

	if !exist {
		log.Info("[cluster]集群不存在，创建新集群")

		ret, err := zookeeper.Connect().Create(c.path, c.data, c.flags, c.acl)
		if err != nil {
			log.Info("==========")
			log.Panic("[cluster]集群创建失败:", err.Error())
		}
		log.Info("[cluster]集群创建成功:", ret)
	} else {
		log.Info("[cluster]集群已经存在")
	}
}
